package com.ma.nio.c2;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.concurrent.atomic.AtomicInteger;

import static com.ma.nio.c1.ByteBufferUtil.debugAll;

/**
 * @ClassName MultiThreadServer
 * @Author: mayongqiang
 * @DATE 2022/4/28 22:34
 * @Description: 多线程的Selector
 */
/* 分两组选择器 Selector   分摊任务  更好地利用Cpu能力
       单线程配一个选择器，专门处理 accept 事件
       创建 cpu 核心数的线程，每个线程配一个选择器，轮流处理 read 事件
*/
@Slf4j
@SuppressWarnings("all")
public class MultiThreadServer {
    public static void main(String[] args) throws IOException, InterruptedException {
        // boss  只负责建立连接
        Thread.currentThread().setName("boss");
        ServerSocketChannel ssc = ServerSocketChannel.open();
        ssc.configureBlocking(false);
        Selector boss = Selector.open();
        SelectionKey bossKey = ssc.register(boss, 0, null);
        bossKey.interestOps(SelectionKey.OP_ACCEPT);
        ssc.bind(new InetSocketAddress(8080));
        // 1、创建固定数量的worker  线程数 ===> cpu核心数
        Worker[] workers = new Worker[Runtime.getRuntime().availableProcessors()];
        for (int i = 0; i < workers.length; i++) {
            workers[i] = new Worker("worker-" + i);
        }
        AtomicInteger index = new AtomicInteger();
        while (true) {
            boss.select();
            Iterator<SelectionKey> iter = boss.selectedKeys().iterator();
            while (iter.hasNext()) {
                SelectionKey key = iter.next();
                iter.remove();
                if (key.isAcceptable()) {
                    SocketChannel sc = ssc.accept();
                    sc.configureBlocking(false);
                    log.debug("connected...{}", sc.getRemoteAddress());
                    // 2、关联Selector
                    log.debug("before register...{}", sc.getRemoteAddress());
                    // round robin 轮询负载均衡
                    workers[index.getAndIncrement() % workers.length].registerInit(sc);  // boss调用 在boss线程中执行该方法  用队列解耦 使方法其在worker线程执行
                    log.debug("after register...{}", sc.getRemoteAddress());

                }
            }
        }
    }

    // worker 单独设计一个类  应该拥有一个独立的线程和选择器
    static class Worker implements Runnable {
        private Thread thread;
        private Selector selector;
        private String name;
        private volatile boolean start = false;  //还未初始化
        private ConcurrentLinkedQueue<Runnable> queue = new ConcurrentLinkedQueue<>();

        public Worker(String name) {
            this.name = name;
        }

        public void registerInit(SocketChannel sc) throws IOException {
            // 向队列中加入一个待执行的任务  将任务在线程间进行了传递
            queue.add(() -> {
                // 用队列解耦 使其在worker线程执行
                try {
                    sc.register(selector, SelectionKey.OP_READ, null); //boss
                } catch (ClosedChannelException e) {
                    throw new RuntimeException(e);
                }
            });
            if (!start) {
                // 初始化线程  执行该类中的run()方法
                selector = Selector.open();
                thread = new Thread(this, name);
                thread.start();
                start = true;
            }
            selector.wakeup();  // 唤醒selector
        }

        @Override
        public void run() {
            while (true) {
                try {
                    selector.select(); //worker-0  阻塞   selector.wakeup()主动唤醒，让select()结束阻塞
                    Runnable task = queue.poll();
                    if (task != null) {
                        task.run();       //执行sc.register(selector, SelectionKey.OP_READ, null);
                    }
                    Iterator<SelectionKey> iter = selector.selectedKeys().iterator();
                    while (iter.hasNext()) {
                        SelectionKey key = iter.next();
                        iter.remove();
                        if (key.isReadable()) {
                            ByteBuffer buffer = ByteBuffer.allocate(16);
                            SocketChannel sc = (SocketChannel) key.channel();
                            log.debug("read...{}", sc.getRemoteAddress());
                            sc.read(buffer);
                            buffer.flip();
                            debugAll(buffer);
                        }
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
